/**
 * 封装axios
 *
 */
import Axios from "axios";
//引入router
// import VueRouter from "../../router";
// const router = VueRouter()
//路由router已经在main.js中引入过，所以此处引用时，不用再调方法，而是直接引入进来对象
import router from "../../router";
const toLogin = () => {
  router.push({
    path: '/login-index'
  }).then(error => {
    console.log('统一配置：转到登录页面有误')
  })
}

/**
 * 错误处理
 */
function errorHandle(status, message) {
  switch (status) {
    case 400:
      console.log("参数有误")
      break
    case 401:
      console.log("认证失败")
      toLogin()
      break
    case 403:
      console.log("token校验失败")
      break
    case 404:
      console.log("客户端错误")
      break
    default:
      console.log(message)
      break
  }
}


//创建axios实例
let axiosInstance = Axios.create({
  timeout: 5000
});
// 在实例已创建后修改默认值  统一axios配置
// axiosInstance.defaults.baseURL = 'http://127.0.0.1:8888';
axiosInstance.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加请求拦截器
axiosInstance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  console.log('发送请求前：', config)
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  response => response.status === 200 ? Promise.resolve(response) : Promise.reject(response),
  error => {
    const {response} = error;
    if(response) {
      errorHandle(response.status, response.data.message);
      return Promise.reject(response);
    } else {
      console.log('断网了');
    }
  }
);

//导出
export default axiosInstance
